import Request from 'luch-request'

import api from '@/config/api'
import { randomString } from '@/utils/foundation'
import storage from '@/utils/storage'

let isNavigateTo = false

async function cleanStorage() {
  uni.showToast({
    title: '你的登录状态已过期，请重新登录',
    icon: 'none'
  })
  storage.setAccessToken('')
  storage.setUuid('')
  storage.setUserInfo({})

  if (!isNavigateTo) {
    isNavigateTo = true
    uni.navigateTo({
      url: '/pages/passport/wechatMPLogin'
    })
  }
}

const http = new Request()

/**
 * 创建uuid方法
 */
function createUuid() {
  if (!storage.getUuid()) storage.setUuid(randomString())
}
const accountInfo = uni.getAccountInfoSync()

http.setConfig((config) => {
  createUuid()
  config.baseURL = api.buyer
  config.header = {
    ...config.header,
    scene: 'STORE',
    appId: accountInfo.miniProgram.appId
  }

  /* 设置全局配置 */
  config.validateStatus = (statusCode) => {
    // 不论什么状态,统一在正确中处理
    return true
  }
  return config
})

http.interceptors.request.use(
  (config) => {
    config.header = {
      ...config.header
    }
    if (config.params) {
      for (const [key, value] of Object.entries(config.params)) {
        if (value === undefined || value === null || value === '') delete config.params[key]
      }
    }
    if (config.data) {
      for (const [key, value] of Object.entries(config.data)) {
        if (value === undefined || value === null || value === '') delete config.data[key]
      }
    }
    /* 请求之前拦截器。可以使用async await 做异步操作 */
    let accessToken = storage.getAccessToken()
    console.log('当前的token', accessToken)
    if (accessToken) {
      const nonce = randomString(6)
      const timestamp = new Date().getTime() / 1000

      const _params = {
        nonce,
        timestamp
      }
      let params = config.params || {}
      params = {
        ...params,
        ..._params
      }

      config.params = params
      config.header = config.header || {}
      config.header.token = accessToken
    }
    createUuid()
    config.header = {
      ...config.header,
      uuid: storage.getUuid()
    }
    return config
  },
  (config) => {
    return Promise.reject(config)
  }
)

// 必须使用异步函数，注意
http.interceptors.response.use(
  async (response) => {
    isNavigateTo = false

    const token = storage.getAccessToken()

    if (
      (!token && response.data.code === 403) ||
      response.data.code === 401 ||
      response.data.code === 20004 ||
      response.statusCode === 403
    ) {
      cleanStorage()
      return Promise.reject(response)
    } else if (response.data.code === 80201) {
      return Promise.resolve(response)
    } else if ((response.data.code === 200 && !response.data.success) || response.data.code !== 200) {
      uni.showToast({
        title: response.data.message || '服务器繁忙，请稍后重试',
        icon: 'none',
        duration: 3000
      })
      return Promise.reject(response)
    }
    return response
  },
  (error) => {
    return error
  }
)

export { http }

interface MethodFace {
  [key: string]: string
}

export const Method: MethodFace = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE'
}
